package com.atguigu.gmall.mq.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.MacSpi;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("mq")
public class MqController {

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    //  发送消息的控制器.
    @GetMapping("sendConfirm")
    public Result sendConfirm(){
        rabbitService.sendMsg("exchange.confirm","routing.confirm","OK");
        return Result.ok();
    }

    //  发送延迟消息
    @GetMapping("sendDelayConfirm")
    public Result sendDelayConfirm(){
        //  延迟10秒钟;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        rabbitService.sendMsg(DeadLetterMqConfig.exchange_dead,DeadLetterMqConfig.routing_dead_1,"delay....");
        //  发送时间。
        System.out.println("发送时间："+simpleDateFormat.format(new Date()));

        return Result.ok();
    }

    //  发送消息：
    @GetMapping("sendDelayMsg")
    public Result sendDelayMsg(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //  基于死信的时候，在队列中设置的延迟时间.
        this.rabbitTemplate.convertAndSend(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay, "delay...ok", message -> {
            //  设置一下延迟时间. 10s;
            message.getMessageProperties().setDelay(10000);
            System.out.println("发送时间："+simpleDateFormat.format(new Date()));
            return message;
        });
        return Result.ok();
    }

}
